import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import * as Tools from '@/utils/tools'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.BASE_URL, // api的base_url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (store.getters.token) {
    config.headers['X-Auth-Token'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
  }
  return config
}, error => {
  // Do something with request error
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  response => {
    /**
     * 下通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
     * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
     */
    const res = response.data
    if (res.code && res.code !== 0) {
      // 10003 非法token
      if (res.code === 10003) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      } else if (res.code === 10005) {
        Message({
          message: '后台系统错误',
          type: 'error',
          duration: 5 * 1000
        })
      }else if(res.code === -2){
        console.log(res)
        MessageBox({
          title: res.message,
          message: Tools.errorMessageBox(res.data),
          dangerouslyUseHTMLString: true,
          confirmButtonText: '关闭',
          showConfirmButton: false,
          customClass: 'errMessageBox',
          beforeClose: (action, instance, done) => {
            done()
          }
        })
      } else {
        Message({
          message: res.msg,
          type: 'error',
          duration: 5 * 1000
        })
        // return response
      }
    } else {
      return response
    }
    return Promise.reject('error')
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

export default service
